package uk.ac.lkl.takteen.energyapp;

import java.util.Calendar;

import uk.ac.lkl.takteen.energyapp.data.EnergyAppDatabaseMetadata;
import uk.ac.lkl.takteen.energyapp.data.EnergyAppProvider;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

public class PledgeEditor extends Activity {

	private Cursor cursor;
	private Uri mUri;

	private EditText mPledgeName;
	private EditText mWhenStatement;
	private EditText mThenStatement;
	private DatePicker mExpiryDate;
	private int mExpiryYear;
	private int mExpiryMonth;
	private int mExpiryDay;

	private static final int COLUMN_INDEX_NAME = 1;
	private static final int COLUMN_INDEX_CREATED_BY = 2;
	private static final int COLUMN_INDEX_CREATED_DATE = 3;
	private static final int COLUMN_INDEX_WHEN = 4;
	private static final int COLUMN_INDEX_THEN = 5;
	private static final int COLUMN_INDEX_YEAR = 6;
	private static final int COLUMN_INDEX_MONTH = 7;
	private static final int COLUMN_INDEX_DAY = 8;

	private int pauseIntent;

	private static final int DELETING = 1;

	// codes for creating dialogs
	private static final int DIALOG_SAVE = 1;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.pledge_editor);

		mPledgeName = (EditText) findViewById(R.id.pledge_name);
		mWhenStatement = (EditText) findViewById(R.id.pledge_when_statement);
		mThenStatement = (EditText) findViewById(R.id.pledge_then_statement);
		mExpiryDate = (DatePicker) findViewById(R.id.pledge_expiry_date_picker);

		final Intent intent = getIntent();
		final String action = intent.getAction();
		mUri = intent.getData();

		if (Intent.ACTION_INSERT.equals(action)) {
			int iDay, iMonth, iYear;

			Calendar cal = Calendar.getInstance();
			iDay = cal.get(Calendar.DAY_OF_MONTH);
			iMonth = cal.get(Calendar.MONTH);
			iYear = cal.get(Calendar.YEAR);

			ContentValues values = new ContentValues();
			values.put(EnergyAppDatabaseMetadata.CREATED_BY, "temp");
			mUri = getContentResolver().insert(getIntent().getData(), values);
		}

		if (Intent.ACTION_EDIT.equals(action)) {

			// get name of the pledge based on uri
			cursor = managedQuery(mUri,
					EnergyAppDatabaseMetadata.PROJECTION_USER_PLEDGES, null,
					null, null);
			cursor.moveToFirst();
			mPledgeName.setText(cursor.getString(COLUMN_INDEX_NAME));
			mPledgeName.setInputType(InputType.TYPE_NULL);
			mWhenStatement.setText(cursor.getString(COLUMN_INDEX_WHEN));
			mThenStatement.setText(cursor.getString(COLUMN_INDEX_THEN));
			mExpiryDate.updateDate(cursor.getInt(COLUMN_INDEX_YEAR),
					cursor.getInt(COLUMN_INDEX_MONTH),
					cursor.getInt(COLUMN_INDEX_DAY));
		}

		final Button makePledgeButton = (Button) findViewById(R.id.make_pledge_button);
		makePledgeButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				savePledge();
				Intent intent = new Intent(Intent.ACTION_VIEW,
						EnergyAppProvider.USER_PLEDGES_DIR, PledgeEditor.this,
						Pledges.class);
				startActivity(intent);
			}
		});

		final Button deletePledgeButton = (Button) findViewById(R.id.delete_pledge_button);
		deletePledgeButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				showDialog(DIALOG_SAVE);
			}
		});

		final Button sharePledgeButton = (Button) findViewById(R.id.share_pledge_button);
		sharePledgeButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				savePledge();
				LinearLayout mPledgeCard = (LinearLayout) findViewById(R.id.pledge_card);
				Bitmap b = Bitmap.createBitmap(mPledgeCard.getWidth(),
						mPledgeCard.getHeight(), Bitmap.Config.ARGB_8888);
				Canvas c = new Canvas(b);
				mPledgeCard.draw(c);

				String challengeCardName = mPledgeName.getText().toString()
						+ " card";
				Uri pledgeCardUri = Uri.parse(MediaStore.Images.Media
						.insertImage(getContentResolver(), b,
								challengeCardName, "Card for "
										+ challengeCardName));
				String mimetype;
				Intent intent = new Intent(Intent.ACTION_SEND);
				mimetype = "image/*";
				intent.putExtra(Intent.EXTRA_STREAM, pledgeCardUri);
				intent.setType(mimetype);
				intent.putExtra(Intent.EXTRA_SUBJECT, mPledgeName.getText()
						.toString());
				try {
					startActivity(Intent.createChooser(intent, "Send to:"));
				} catch (android.content.ActivityNotFoundException ex) {
					Toast.makeText(PledgeEditor.this,
							"No apps registered for this intent",
							Toast.LENGTH_SHORT).show();
				}
			}
		});

	}

	@Override
	public void onBackPressed() {
		Log.d("CDA", "onBackPressed Called");
		final Intent intent = getIntent();
		final String action = intent.getAction();
		if (Intent.ACTION_INSERT.equals(action)) {
			String name = mPledgeName.getText().toString();
			String pledgeWhenStatement = mWhenStatement.getText().toString();
			String pledgeThenStatement = mThenStatement.getText().toString();
			if (name.length() != 0 || pledgeWhenStatement.length() != 0
					|| pledgeThenStatement.length() != 0)
				showDialog(DIALOG_SAVE);
			else {
				Intent newIntent = new Intent(Intent.ACTION_VIEW, null,
						PledgeEditor.this, EnergyAppActivity.class);
				startActivity(newIntent);
			}
		} else {
			savePledge();
			Intent newIntent = new Intent(Intent.ACTION_VIEW,
					EnergyAppProvider.USER_PLEDGES_DIR, PledgeEditor.this,
					Pledges.class);
			startActivity(newIntent);
		}
	}

	protected Dialog onCreateDialog(int id) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		switch (id) {
		case DIALOG_SAVE:
			builder.setTitle("Save")
					.setMessage("Do you want to save this challenge?")
					.setPositiveButton("Save",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									savePledge();
									dialog.cancel();
									if (Intent.ACTION_INSERT.equals(getIntent()
											.getAction())) {
										Intent intent = new Intent(
												Intent.ACTION_VIEW, null,
												PledgeEditor.this,
												EnergyAppActivity.class);
										startActivity(intent);
									} else if (Intent.ACTION_EDIT
											.equals(getIntent().getAction())) {
										Intent intent = new Intent(
												Intent.ACTION_VIEW,
												EnergyAppProvider.USER_PLEDGES_DIR,
												PledgeEditor.this,
												Pledges.class);
										startActivity(intent);
									}
								}
							})
					.setNegativeButton("Delete",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									pauseIntent = DELETING;
									cursor = null;
									String whenSelectionStatement = EnergyAppDatabaseMetadata._ID
											+ "=" + mUri.getLastPathSegment();
									getContentResolver().delete(
											EnergyAppProvider.USER_PLEDGES_DIR,
											whenSelectionStatement, null);
									dialog.cancel();
									if (Intent.ACTION_INSERT.equals(getIntent()
											.getAction())) {
										Intent intent = new Intent(
												Intent.ACTION_VIEW, null,
												PledgeEditor.this,
												EnergyAppActivity.class);
										startActivity(intent);
									} else if (Intent.ACTION_EDIT
											.equals(getIntent().getAction())) {
										Intent intent = new Intent(
												Intent.ACTION_VIEW,
												EnergyAppProvider.USER_PLEDGES_DIR,
												PledgeEditor.this,
												Pledges.class);
										startActivity(intent);
									}
								}
							});
			break;
		default:

		}
		return builder.create();
	}

	public void savePledge() {

		String name = mPledgeName.getText().toString();
		if (name.length() == 0)
			name = "Nameless pledge";
		String pledgeWhenStatement = mWhenStatement.getText().toString();
		String pledgeThenStatement = mThenStatement.getText().toString();
		int mExpiryYear = mExpiryDate.getYear();
		int mExpiryMonth = mExpiryDate.getMonth();
		int mExpiryDay = mExpiryDate.getDayOfMonth();
		ContentValues values = new ContentValues();
		values.put(EnergyAppDatabaseMetadata.PLEDGE_NAME, name);
		values.put(EnergyAppDatabaseMetadata.WHEN_STATEMENT,
				pledgeWhenStatement);
		values.put(EnergyAppDatabaseMetadata.THEN_STATEMENT,
				pledgeThenStatement);
		values.put(EnergyAppDatabaseMetadata.EXPIRATION_YEAR, mExpiryYear);
		values.put(EnergyAppDatabaseMetadata.EXPIRATION_MONTH, mExpiryMonth);
		values.put(EnergyAppDatabaseMetadata.EXPIRATION_DAY, mExpiryDay);
		// add to database
		// if intent is view then update
		// if intent is insert then create a new one
		if (Intent.ACTION_INSERT.equals(getIntent().getAction())) {
			values.put(EnergyAppDatabaseMetadata.CREATED_BY, "temp");
			values.put(EnergyAppDatabaseMetadata.DATE_CREATED, "null");
			getContentResolver().insert(getIntent().getData(), values);
		} else if (Intent.ACTION_EDIT.equals(getIntent().getAction())) {
			String whenSelectionStatement = EnergyAppDatabaseMetadata._ID + "="
					+ getIntent().getFlags();
			getContentResolver().update(getIntent().getData(), values,
					whenSelectionStatement, null);
		}
	}
}
